import React, {Component} from 'react'
import Cropper from 'cropperjs'
import {modal, upload} from '../../common/js/utils'
import 'cropperjs/dist/cropper.css'
import dataURLtoBlob from 'blueimp-canvas-to-blob'
import DefaultLayout from '../../layouts/default_layout'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import {setUserInfo} from '../../actions'
import {NavBar, Icon, Button} from 'antd-mobile'

function mapStateToProps(state, props) {
  return {
    userInfo: state.userInfo
  }
}

const mapDispatchToProps = dispatch => {
  return {
    setUserInfo(value) {
      dispatch(setUserInfo(value))
    }
  }
}

@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class Avatar extends Component {

  state = {
    img: ''
  }

  componentDidMount() {
    this.renderCropper()
  }

  componentDidUpdate() {
    // this.renderCropper()
  }

  renderCropper = () => {
    const options = {
      aspectRatio: 1,
      viewMode: 1,
      minCropBoxWidth: 100,
      movable: false, // 是否能拖动图片
      scalable: false,
      zoomable: false
    }
    this.crop = new Cropper(document.getElementById('faceId'), options)
  }

  doUpload = () => {
    if (!this.crop) return
    const canvas = this.crop.getCroppedCanvas({
      width: 400,
      height: 400
    })
    const handleBlob = (blob) => {
      const form = new FormData()
      form.append('file', blob, 'avatar.png')
      this.uploadToServer(form)
    }
    if (canvas.toBlob) {
      canvas.toBlob(handleBlob)
    } else {
      dataURLtoBlob(canvas.toDataURL(), handleBlob)
    }
  }

  uploadToServer = data => {
    const {history, userInfo, setUserInfo} = this.props
    upload('/users/avatar', data, {}, loading => { modal.loading(loading) }).then(res => {
      if (res.result === 1) {
        const info = Object.assign({}, userInfo)
        info.avatar = res.data
        setUserInfo(info)
        modal.toast(res.mes)
        history.go(-1)
      }
    })
  }

  handleImg = (e) => {
    const file = e.target.files[0]
    if (file && this.crop) {
      if (this.tempImg) {
        URL.revokeObjectURL(this.tempImg)
      }
      this.tempImg = URL.createObjectURL(file)
      this.crop.replace(this.tempImg)
    }
  }

  render() {
    const {history} = this.props
    const img = this.state.img || this.props.userInfo.avatar
    return (
      <DefaultLayout
        header={
          <NavBar
            mode="light"
            icon={<Icon type="left" />}
            onLeftClick={() => {
              history.go(-1)
            }}
            rightContent={
              <Button
                type={'ghost'}
                onClick={this.doUpload}
                size={'small'}
              >保存</Button>
            }
          >修改头像</NavBar>
        }
        footer={
          <div className="input-file">
            <input type="file" accept="image/*" onChange={this.handleImg} />
            <Button
              type={'primary'}
              size={'large'}
            >选择图片</Button>
          </div>
        }
      >
        <div
          className="scroll-view flex-row align-center justify-center"
        >
          <img id="faceId" src={img} alt="修改头像"/>
        </div>
      </DefaultLayout>
    )
  }
}

export default Avatar